package model

import (
	"time"

	"gorm.io/gorm"
)

/*  有关Type的说明
1. comment_like     评论点赞
2. passage_like     文章点赞
3. passage_comment  文章评论
4. comment_comment  回复评论
5. check_notice     领养方发出领养申请后，系统生成一条提醒发起方查看的通知
6. request_fail		发起方不通过领养，系统生成一条告知领养方申请不通过的通知
7. request_success  发起方通过领养，系统生成一条告知领养方申请通过的通知
8. adopt_fail		发起方选择领养失败后，系统生成一条告知领养方领养失败的通知
9. adopt_success	发起方选择领养成功后，系统生成一条提醒领养方查看的通知
10. comment_notice	在领养申请通过后，领养双方可以对发起方进行评价，评价后系统生成一条提醒发起方查看的通知
ps. 其中评价相关消息需填充CommentID字段, 领养相关消息需填充AdoptID字段
*/

type Message struct {
	MessageID  int    `gorm:"primaryKey; autoIncrement"`
	PassageID  int    `gorm:"not null"`
	Type       string `gorm:"not null"`
	SenderID   int    `gorm:"null"`
	ReceiverID int    `gorm:"null"`
	CommentID  int    `gorm:"null"`
	AdoptID    int    `gorm:"null"`
	CreatedAt  time.Time
	State      bool           `gorm:"not null; default: false"`
	DeletedAt  gorm.DeletedAt `gorm:"index"`
	Passage    *Passage       `gorm:"foreignKey:PassageID; references:PassageID"`
}

func (m *Message) SaveMessage() (*Message, error) {
	err := DB.Create(&m).Error
	if err != nil {
		return &Message{}, err
	}
	return m, nil
}

func GetLikeMessageByID(id int) (*[]Message, error) {
	var messages *[]Message
	err := DB.Order("CreatedAt desc").Where("ReceiverID = ? and Type in ('comment_like', 'passage_like')", id).Find(&messages).Error
	if err != nil {
		return &[]Message{}, err
	}
	return messages, nil
}

func GetCommentMessageByID(id int) (*[]Message, error) {
	var messages *[]Message
	err := DB.Order("CreatedAt desc").Where("ReceiverID = ? and Type in ('passage_comment', 'comment_comment')", id).Find(&messages).Error
	if err != nil {
		return &[]Message{}, err
	}
	return messages, nil
}

func GetAdoptMessageByID(id int) (*[]Message, error) {
	var messages *[]Message
	err := DB.Order("CreatedAt desc").Where("ReceiverID = ? and Type in ('check_notice', 'request_fail', 'request_success', 'adopt_fail', 'adopt_success','comment_notice')", id).Find(&messages).Error
	if err != nil {
		return &[]Message{}, err
	}
	return messages, nil
}

func (m *Message) IsLikeOccured() (bool, error) {
	var count int64
	err := DB.Model(Message{}).Where("PassageID = ? and CommentID = ? and SenderID = ? and ReceiverID = ? and Type = ?", m.PassageID, m.CommentID, m.SenderID, m.ReceiverID, m.Type).Count(&count).Error
	if err != nil {
		return false, err
	}

	if count > 0 {
		return true, nil
	} else {
		return false, nil
	}
}
